#include "LoadBalanceStrategy.h"
#include "SubReactor.h"
#include <cstdint>
#include <iostream>

using std::cout;
using std::endl;

void ConsistentHash::addReactor(SubReactor* reactor, int reactorId) {
    // 为每个SubReactor创建多个虚拟节点，提高分布均匀性
    for (int i = 0; i < VIRTUAL_NODES; ++i) {
        std::string vnode = std::to_string(reactorId) + "_" + std::to_string(i);
        uint32_t hash = hashFunction(vnode);
        _ring[hash] = reactor;
    }
    cout << "[ConsistentHash] 添加Reactor-" << reactorId 
         << " 虚拟节点数=" << VIRTUAL_NODES << endl;
}

void ConsistentHash::removeReactor(int reactorId) {
    // 移除该reactor的所有虚拟节点
    for (int i = 0; i < VIRTUAL_NODES; ++i) {
        std::string vnode = std::to_string(reactorId) + "_" + std::to_string(i);
        uint32_t hash = hashFunction(vnode);
        _ring.erase(hash);
    }
    cout << "[ConsistentHash] 移除Reactor-" << reactorId << endl;
}

SubReactor* ConsistentHash::getReactor(const std::string& clientIP) {
    if (_ring.empty()) {
        return nullptr;
    }
    
    uint32_t hash = hashFunction(clientIP);
    
    // 在哈希环上找到第一个大于等于该哈希值的节点
    auto it = _ring.lower_bound(hash);
    
    // 如果超出范围，回到环的开始（体现了"环"的特性）
    if (it == _ring.end()) {
        it = _ring.begin();
    }
    
    return it->second;
}

void ConsistentHash::clear() {
    _ring.clear();
}

uint32_t ConsistentHash::hashFunction(const std::string& key) {
    // 使用FNV-1a哈希算法，分布性较好
    uint32_t hash = 2166136261u;
    for (char c : key) {
        hash ^= static_cast<uint32_t>(static_cast<unsigned char>(c));
        hash *= 16777619u;
    }
    return hash;
}